package com.wolfalpha.utron.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseCenterActivity;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.app.AppManager;
import com.wolfalpha.utron.bean.UserInfo;
import com.wolfalpha.utron.service.UserService;
import com.wolfalpha.utron.service.impl.UserServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.FileUtils;
import com.wolfalpha.utron.utils.ImageUtils;
import com.wolfalpha.utron.utils.ThreadPoolUtils;
import com.wolfalpha.utron.view.CircleImageView;
import com.wolfalpha.utron.view.ListAlertDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 个人中心界面
 *
 * @author luodon
 */
public class UserCenterActivity extends BaseCenterActivity implements View.OnClickListener {

    public static final String HEAD_CHANGED = "user.head.changed";//头像变化广播

    private LinearLayout lyIdea;            //我的想法
    private LinearLayout lyProject;         //我的项目
    private LinearLayout lyPartner;         //我是合伙人
    private LinearLayout lyDetail;          //详细资料

    private CircleImageView ivHead;         //用户头像

    private TextView tvNickName;            //用户昵称文字
    private TextView tvAttention;           //用户被关注度
    private TextView tvVisit;               //来访次数


    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESIZE_REQUEST_CODE = 2;
    private static final int DATA_OK = 3;


    private static final String IMAGE_FILE_NAME = "utron/imageCache/user_header.jpg";//头像拍照路径

    private UserService userService;

    private UserInfo userInfo;
    private Bitmap photo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        System.out.println("Center");

        if ((userInfo = AppContext.getInstance().getUserInfo()) == null) {
            UIHelper.showActivityAndFinish(UserCenterActivity.this, LoginActivity.class);
            return;
        }
        if (userInfo.getUser_id() != AppContext.getInstance().getUserId()) {
            UIHelper.showActivityAndFinish(UserCenterActivity.this, UserInfoActivity.class);
            return;
        }

        setContentView(R.layout.activity_user_center);
        userService = new UserServiceImpl();

        initHead();
        initView();
        initListeners();
        AppManager.getAppManager().addActivity(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        userInfo = AppContext.getInstance().getUserInfo();
        initText();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
    }

    /**
     * 初始化界面
     */
    private void initView() {

        lyIdea = (LinearLayout) findViewById(R.id.ly_user_center_go_idea);
        lyProject = (LinearLayout) findViewById(R.id.ly_user_center_go_project);
        lyPartner = (LinearLayout) findViewById(R.id.ly_user_center_go_partner);
        lyDetail = (LinearLayout) findViewById(R.id.ly_user_center_go_detail);

        ivHead = (CircleImageView) findViewById(R.id.ci_user_center_head);

        tvNickName = (TextView) findViewById(R.id.tv_user_center_nickname);
        tvAttention = (TextView) findViewById(R.id.tv_user_center_attention);
        tvVisit = (TextView) findViewById(R.id.tv_user_center_visit);

        if (ImageUtils.getBitmap(AppContext.getInstance(), "head_pic.jpg") != null)
            ivHead.setImageBitmap(ImageUtils.getBitmap(UserCenterActivity.this, "head_pic.jpg"));
    }

    /**
     * 设置内容
     */
    private void initText() {
        tvNickName.setText(userInfo.getNickname());
        tvAttention.setText(String.valueOf(userInfo.getAttention()) + " 人关注");
        tvVisit.setText(String.valueOf(userInfo.getVisit()) + " 次访问");
    }

    /**
     * 初始化监听
     */
    private void initListeners() {
        lyIdea.setOnClickListener(this);
        lyProject.setOnClickListener(this);
        lyPartner.setOnClickListener(this);
        lyDetail.setOnClickListener(this);
        ivHead.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ly_user_center_go_idea:
                //我的想法
                UIHelper.showActivity(UserCenterActivity.this, MyIdeasActivity.class);
                break;
            case R.id.ly_user_center_go_project:
                //我的项目
                UIHelper.showActivity(UserCenterActivity.this, MyProjectsActivity.class);
                break;
            case R.id.ly_user_center_go_partner:
                //我是合伙人
                Bundle bundle1 = new Bundle();
                bundle1.putInt("userId", AppContext.getInstance().getUserId());
                UIHelper.showActivity(UserCenterActivity.this, PartnerInfoSelfActivity.class, bundle1);
                break;
            case R.id.ly_user_center_go_detail:
                //详细资料
                Intent intent = new Intent(UserCenterActivity.this, UserInfoDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("userInfo", userInfo);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.ci_user_center_head:
                //用户头像
                showPickPhoto();
                break;
        }
    }

    /**
     * 选召唤类型
     */
    private void showPickPhoto() {
        final ListAlertDialog ad = new ListAlertDialog(UserCenterActivity.this);
        ad.setTitle("选择头像");
        final String[] arr = new String[]{"本地上传", "拍照"};
        ad.setArray(arr);
        ad.setOnFinishedListener(new ListAlertDialog.OnFinishedListener() {
            @Override
            public void finish(int input) {
                if (input == 0) {
                    //本地上传
                    Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
                    galleryIntent.setType("image/*");
                    startActivityForResult(galleryIntent, IMAGE_REQUEST_CODE);
                }
                if (input == 1) {
                    //拍照上传
                    if (FileUtils.checkSDExists()) {
                        Intent cameraIntent = new Intent(
                                "android.media.action.IMAGE_CAPTURE");
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
                        cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                        startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                    } else {
                        UIHelper.ToastMessage(UserCenterActivity.this, "请先插入SD卡");
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        } else {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    resizeImage(data.getData());
                    break;
                case CAMERA_REQUEST_CODE:
                    if (FileUtils.checkSDExists()) {
                        resizeImage(getImageUri());
                    } else {
                        UIHelper.ToastMessage(UserCenterActivity.this, "没有存储卡");
                    }
                    break;

                case RESIZE_REQUEST_CODE:
                    if (data != null) {
                        showResizeImage(data);
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 对图片进行裁剪
     *
     * @param uri
     */
    public void resizeImage(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra("output", getImageUri());  // 传入目标文件
        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", "JPEG"); //输入文件格式
        startActivityForResult(intent, RESIZE_REQUEST_CODE);
    }

    File f = null;

    /**
     * 显示头像图片
     *
     * @param data
     */
    private void showResizeImage(Intent data) {
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                ThreadPoolUtils.execute(new Runnable() {
                    @Override
                    public void run() {
                        String newUrl = userService.updateUserHead(f);
                        userInfo.setHead_pic(newUrl);
                        AppContext.getInstance().initUserInfo(userInfo);
                        AppContext.getInstance().saveObject(userInfo, "userInfo");
                    }
                });
            }
        };
        Bundle extras = data.getExtras();
        if (extras != null) {
            photo = extras.getParcelable("data");
            try {
//              ImageUtils.saveImage(this,"user_head.jpg",photo);

                f = getImage();
                FileOutputStream fOut = null;
                try {
                    fOut = new FileOutputStream(f);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                photo.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                fOut.flush();
                fOut.close();
                if (f != null) handler.sendEmptyMessage(0);
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                ImageUtils.saveImage(AppContext.getInstance(), "head_pic.jpg", photo);
                Intent intent = new Intent();
                intent.setAction(HEAD_CHANGED);        //设置Action
                sendBroadcast(intent);//广播通知
            } catch (IOException e) {
                e.printStackTrace();
            }

            Drawable drawable = new BitmapDrawable(photo);
            ivHead.setImageDrawable(drawable);
        }
    }

    /**
     * 获取图像地址
     *
     * @return
     */
    private Uri getImageUri() {
        return Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME));
    }

    /**
     * 获取图片内容
     *
     * @return
     */
    private File getImage() {
        return new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME);
    }

}
